package cn.acmenms.controller;

import cn.acmenms.annotation.IgnoreSecurity;
import cn.acmenms.exception.BusinessException;
import cn.acmenms.po.enums.ResponseCode;
import cn.acmenms.po.enums.TimeFormatEnum;
import cn.acmenms.po.model.Calendar4SignIn;
import cn.acmenms.po.model.SignIn;
import cn.acmenms.po.model.SignInInfo;
import cn.acmenms.po.query.SignInQuery;
import cn.acmenms.po.vo.AjaxResponse;
import cn.acmenms.po.vo.PaginationResult;
import cn.acmenms.service.SignInService;
import cn.acmenms.utils.Constants;
import cn.acmenms.utils.LocalDateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SignInController
 * @Description: 签到Controller
 * @author: 神奇的鸭鸭
 * @Date: 2018/2/10 18:06
 */
@RestController
public class SignInController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(SignInController.class);

    @Resource
    private SignInService signInService;

    /**
     * 获取签到页面回显信息
     * @param request 请求头
     * @return 结果集
     */
    @IgnoreSecurity
    @RequestMapping(value = "/signIn", method = RequestMethod.GET)
    public AjaxResponse<SignInInfo> signIn(HttpServletRequest request) {
        AjaxResponse<SignInInfo> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {
            SignInInfo signInInfo;
            // 有token就校验用户是否签到，没有就不校验
            String header = request.getHeader(Constants.DEFAULT_TOKEN_NAME);
            System.out.println(header);
            if (!"undefined".equalsIgnoreCase(request.getHeader(Constants.DEFAULT_TOKEN_NAME))) {
                signInInfo = this.signInService.findSignInInfoByUserId(this.getTokenUser(request).getUserId());
            } else {
                signInInfo = this.signInService.findSignInInfoByUserId(null);
            }
            result.setData(signInInfo);
        } catch (BusinessException e) {
            logger.error("获取用户今日签到记录失败", e);
            result.setResponseCode(ResponseCode.BUSINESSERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("获取用户今日签到记录失败", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("获取用户今日签到记录失败");
        }
        return result;
    }

    /**
     * 用户签到
     * @param request 请求头
     * @return 用户签到结果
     */
    @RequestMapping(value = "/doSignIn", method = RequestMethod.GET)
    public AjaxResponse<SignIn> doSignIn(HttpServletRequest request) {
        AjaxResponse<SignIn> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {
            SignIn signIn = this.signInService.doSignIn(this.getTokenUser(request), this.getUserAgent(request));
            result.setData(signIn);
        } catch (BusinessException e) {
            logger.error("签到异常", e);
            result.setResponseCode(ResponseCode.BUSINESSERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("签到异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("签到异常，服务器发生严重错误");
        }
        return result;
    }

    /**
     * 加载今日签到信息 - 分页
     * @param pageNum 查询条件 - 第几页
     * @return 第几页的签到信息
     */
    @IgnoreSecurity
    @RequestMapping(value = "/loadCurDaySignIn", method = RequestMethod.GET)
    public AjaxResponse<PaginationResult<SignIn>> loadCurDaySignIn(Integer pageNum) {
        AjaxResponse<PaginationResult<SignIn>> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {
            SignInQuery query = new SignInQuery();
            query.setPageNum(pageNum);
            PaginationResult<SignIn> data = this.signInService.findCurDaySigIn(query);
            result.setData(data);
        } catch (BusinessException e) {
            logger.error("获取今日签到信息异常", e);
            result.setResponseCode(ResponseCode.BUSINESSERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("获取今日签到信息异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("获取今日签到异常");
        }
        return result;
    }

    /**
     * 根据年份加载用户签到信息
     * @param year 年份
     * @return 用户签到信息
     */
    @RequestMapping(value = "/loadUserSignIn", method = RequestMethod.GET)
    public AjaxResponse<Map<String, Object>> loadUserSignIn(HttpServletRequest request, Integer year) {
        AjaxResponse<Map<String, Object>> result = new AjaxResponse<>();
        try {
            HashMap<String, Object> resultData = new HashMap<>();
            List<Calendar4SignIn> data = this.signInService.findUserSignInByYear(this.getTokenUser(request).getUserId(), year);
            resultData.put("list", data);
            resultData.put("curYear", LocalDateTimeUtils.parseTime(LocalDateTime.now(), TimeFormatEnum.YYYY));
            resultData.put("year", year);
            result.setData(resultData);
            result.setResponseCode(ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("获取用户签到信息失败", e);
            result.setResponseCode(ResponseCode.BUSINESSERROR);
            result.setErrorMsg("获取用户签到信息失败");
        }
        return result;
    }
}